import { defineComponent, reactive, onMounted, computed, ref } from "vue";
import { notification, Form } from "ant-design-vue";
import { formLayoutProps } from "@/components/props";
import { API, requests } from "@/api";
import { PlusOutlined } from '@ant-design/icons-vue';

const useForm = Form.useForm;

function getBase64(file: File) {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => resolve(reader.result);
        reader.onerror = (error) => reject(error);
    });
}

export default defineComponent({
    components: {
        PlusOutlined,
    },
    emits: ["finish", "close"],
    setup(props: any, { emit }) {
        const form = {
            modelRef: reactive<any>({
                goods_name: undefined,
                goods_price: null,
                goods_num: null,
                goods_img: undefined,
            }),
            rulesRef: reactive({
                goods_name: [
                    {
                        required: true,
                        message: "请输入商品的名称",
                    },
                ],
                goods_price: [
                    {
                        required: true,
                        message: "请输入商品的价格",
                    },
                ],
                goods_num: [
                    {
                        required: true,
                        message: "请输入商品的数量",
                    },
                ],
                goods_img: [
                    {
                        required: true,
                        message: "需上传商品图片",
                    },
                ],
            }),
            onClose: () => {
                emit("close");
            },
        };

        const previewVisible = ref<boolean>(false);
        const previewImage = ref<string | undefined>("");
        const fileList: any = ref([
            // {
            //   uid: '8748748481',
            //   name: 'image.png',
            //   status: 'done',
            //   url:
            //     'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
            // },
        ]);

        const handlePreview = async (file:any) => {
            if (!file.url && !file.preview) {
                file.preview = (await getBase64(file.originFileObj)) as string;
            }
            previewImage.value = file.url || file.preview;
            previewVisible.value = true;
        };

        const handleChange = ({ fileList: newFileList }: any) => {
            fileList.value = newFileList;
            fileList.value.map((el: any, index: any) => {
                if (el.response) {
                    form.modelRef.goods_img = fileList.value[index].response.result.goods_img;
                }
            });
        };
        const handleCancel = () => {
            previewVisible.value = false;
        };
        const handleFileRemove = (file: any) => {
        };
        const { validate, validateInfos } = useForm(form.modelRef, form.rulesRef);

        const onSubmit = (e: any) => {
            e.preventDefault();
            validate()
                .then((res) => {

                    requests({
                        url: API.goods.product,
                        data: form.modelRef,
                    }).then((res: any) => {
                        //console.log(res);
                        emit("finish");
                    })
                    // console.log(res);
                    // console.log("先调保存的接口");
                    // console.log("在把modal框关闭,提示成功");
                    // notification["success"]({
                    //     message: "提示",
                    //     description: "添加成功！",
                    // });
                    //console.log("在父组件也调用查询接口刷新页面的元素");
                })
                .catch((err) => {
                    console.log(err);
                    notification["error"]({
                        message: "校验失败!",
                    });
                });
        };


        return () => (
            <a-form
                label-col={formLayoutProps.labelCol}
                wrapper-col={formLayoutProps.wrapperCol}
                {...form.modelRef}
            >
                <a-form-item label="商品名称" {...validateInfos["goods_name"]}>
                    <a-input v-model={[form.modelRef.goods_name, "value"]} allowClear />
                </a-form-item>
                <a-form-item label="商品价格" {...validateInfos["goods_price"]}>
                    <a-input-number
                        v-model={[form.modelRef.goods_price, "value"]} allowClear
                        formatter={(value: number) => `$ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
                        parser={(value: any) => value.replace(/\$\s?|(,*)/g, '')}
                        style="width:200px"
                    />  元
                </a-form-item>
                <a-form-item label="商品数量" {...validateInfos["goods_num"]}>
                    <a-input-number v-model={[form.modelRef.goods_num, "value"]} allowClear min={1} max={1000} />  件
                </a-form-item>
                <a-form-item label="商品图片" {...validateInfos["goods_img"]}>
                    <a-upload
                        list-type="picture-card"
                        name="file"
                        v-model={[fileList.value, "fileList"]}
                        multiple={true}
                        action="/api/goods/upload"
                        headers={{
                            Authorization:
                                "Bearer " + sessionStorage.getItem("token"),
                        }}
                        onChange={handleChange}
                        remove={handleFileRemove}
                        onPreview={handlePreview}
                    >
                        {fileList.value.length < 1 ? (
                            <div>
                                <plus-outlined />
                                <div class="ant-upload-text">上传图片</div>
                            </div>
                        ) : (
                            ""
                        )}
                    </a-upload>
                    <a-modal
                        visible={previewVisible.value}
                        footer={null}
                        onCancel={handleCancel}
                    >
                        <img alt="example" style="width: 100%" src={previewImage.value} />
                    </a-modal>
                </a-form-item>
                <a-form-item wrapper-col={formLayoutProps.submitWrapperCol}>
                    <div class="modal_footer">
                        <a-button
                            style={{ display: "inline" }}
                            type="primary"
                            html-type="submit"
                            onClick={onSubmit}
                        >
                            保存
                        </a-button>
                        <a-button
                            style={{ display: "inline", marginLeft: "10px" }}
                            onClick={form.onClose}
                        >
                            关闭
                        </a-button>
                    </div>
                </a-form-item>
            </a-form>
        );
    },
});
